#include"Sock.hpp"
#include<pthread.h>
#include<stdlib.h>
#include<cstring>
#include<unistd.h>
using namespace std;
using namespace wyl;



//处理线程
void* HandlerHttpRequest(void* args)
{
    int sock = *(int*)args;
    delete (int*)args;
    //提供短服务
#define NUM 1024*10
    char buffer[NUM];
    memset(buffer,0,sizeof(buffer));
    ssize_t s = recv(sock,buffer,sizeof(buffer)-1,0);
    if(s > 0)
    {
        //读取成功
        cout<<buffer;

        //给客户端发送响应
        std::string resp_string = "http/1.0 200 OK\n"; //响应
        resp_string += "Content-Type: text/plain\n";//text/plain 是普通文本
        resp_string += "\n" ; //空行
        resp_string += "hello,my friend!";
        send(sock,resp_string.c_str(),resp_string.size(),0);
    }
    else
    {
        cout<<"recv failed"<<endl;
    }
    close(sock);
    return nullptr;
}


void Usage(string us)
{
    cout<<"Usage ： "<< us <<" port"<<endl;
}

int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
    }

    //创建
    int listen_sock = Sock::Socket();
    //绑定
    Sock::Bind(listen_sock,atoi(argv[1]));
    //监听
    Sock::Listen(listen_sock);

    while(true)
    {
        //等待连接
        int new_sock = Sock::Accpet(listen_sock);
        int* parem = new int (new_sock);
        //创建线程
        pthread_t tid;
        pthread_create(&tid,nullptr,HandlerHttpRequest,(void*)parem); 
    }
    

    return 0;
}